package org.f0rb.demo.utils;


/**
 * Class org.f0rb.demo.utils description goes here.
 *
 * @author Administrator
 * @version 1.0.0 11-10-7
 */
public class StringUtils extends org.apache.commons.lang.StringUtils {
    /**
     * 获取用户访问URL中的根域名.
     * 例如: www.baidu.com -> baidu.com
     *
     * @param host the host name
     * @return DomainOfServerName
     */
    public static String getDomainOfServerName(String host) {
        if (isIPAddr(host))
            return null;
        String[] names = StringUtils.split(host, '.');
        int len = names.length;
        if (len == 1) return null;
        if (len == 3) {
            return makeup(names[len - 2], names[len - 1]);
        }
        if (len > 3) {
            String dp = names[len - 2];
            if (dp.equalsIgnoreCase("com")
                    || dp.equalsIgnoreCase("gov")
                    || dp.equalsIgnoreCase("net")
                    || dp.equalsIgnoreCase("edu")
                    || dp.equalsIgnoreCase("org"))
                return makeup(names[len - 3], names[len - 2], names[len - 1]);
            else
                return makeup(names[len - 2], names[len - 1]);
        }
        return host;
    }

    /**
     * 判断字符串是否是一个IP地址.
     *
     * @param addr a String Object
     * @return true if the input is an IP address, otherwise false.
     */
    public static boolean isIPAddr(String addr) {
        if (StringUtils.isEmpty(addr))
            return false;
        String[] ips = StringUtils.split(addr, '.');
        if (ips.length != 4)
            return false;
        try {
            int ipa = Integer.parseInt(ips[0]);
            int ipb = Integer.parseInt(ips[1]);
            int ipc = Integer.parseInt(ips[2]);
            int ipd = Integer.parseInt(ips[3]);
            return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <= 255 && ipc >= 0
                    && ipc <= 255 && ipd >= 0 && ipd <= 255;
        } catch (NumberFormatException ignored) {
        }
        return false;
    }

    private static String makeup(String... ps) {
        StringBuilder s = new StringBuilder();
        for (int idx = 0; idx < ps.length; idx++) {
            if (idx > 0) s.append('.');
            s.append(ps[idx]);
        }
        return s.toString();
    }
}
